package com.common;


import javax.net.ssl.SSLContext;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;

/**
 * 
 * @author  HuYaHui
 * @version $Revision:1.0.0, $Date: 2015年9月24日 下午9:20:57 $ 
 *
 */
public class HttpClientFactory {
	public static CloseableHttpClient getDefaultHttpClient(String url,RequestConfig config) throws Exception{
		BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(ignoringSSL()); 
	    cm.setSocketConfig(
	    		SocketConfig.custom().
	    			setSoTimeout(config.getSocketTimeout()).build());
		HttpClientBuilder builder = HttpClients.custom()
	    		.setConnectionManager(cm)
	    		.setDefaultRequestConfig(config);     
		CloseableHttpClient httpClient = builder.build();
		return httpClient;
	}
	
	public static RequestConfig getRequestConfig(int timeout){
		Builder requestBuilder = RequestConfig.custom()
				.setSocketTimeout(timeout)
				.setConnectTimeout(timeout)
				.setConnectionRequestTimeout(timeout);
		return requestBuilder.build();
	}

	private static Registry<ConnectionSocketFactory> ignoringSSL() throws Exception{
		SSLContextBuilder builder = SSLContexts.custom();
	    builder.loadTrustMaterial(null, new TrustStrategy(){
			public boolean isTrusted(
					java.security.cert.X509Certificate[] chain,
					String authType)
					throws java.security.cert.CertificateException {
				return true;
			}
	    });
	    SSLContext sslContext = builder.build();
	    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext,new NoopHostnameVerifier());
	    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
	            .<ConnectionSocketFactory> create()
	            .register("https", sslsf)
	            .register("http", new PlainConnectionSocketFactory())
	            .build();
	    return socketFactoryRegistry;
	}
}
